import { Provide } from '@midwayjs/core';
import { BaseService, CoolCommException } from '@cool-midway/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import { UserEmailCodeEntity } from '../entity/email';
import * as nodemailer from 'nodemailer';
import { CoolConfig } from '@cool-midway/core';
import { Config } from '@midwayjs/core';

/**
 * 邮箱验证码
 */
@Provide()
export class UserEmailService extends BaseService {
  @InjectEntityModel(UserEmailCodeEntity)
  userEmailCodeEntity: Repository<UserEmailCodeEntity>;

  @Config('cool')
  coolConfig: CoolConfig;

  /**
   * 发送验证码
   * @param email 邮箱
   * @param type 类型 0-注册 1-修改密码
   */
  async sendCode( body:{email: string, type: number}) {
    const { email, type } = body;
    console.log('email',email);
    console.log('type',type ,  typeof type);
    // 检查邮箱格式
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(email)) {
      throw new CoolCommException('邮箱格式不正确');
    }

    // 检查是否频繁发送
    const lastCode = await this.userEmailCodeEntity.findOne({
      where: { email, type },
      order: { createTime: 'DESC' },
    });

    if (lastCode && Date.now() - lastCode.createTime.getTime() < 60000) {
      throw new CoolCommException('请1分钟后再试');
    }

    // 生成验证码
    const code = Math.random().toString().slice(-6);
    const expireTime = new Date(Date.now() + 10 * 60 * 1000); // 10分钟有效期

    // 保存验证码
    await this.userEmailCodeEntity.save({
      email,
      code,
      type,
      expireTime,
    });

    console.log('this.coolConfig.email',this.coolConfig.email);

    // 发送邮件
    const transporter = nodemailer.createTransport({
      host: this.coolConfig.email.host,
      port: this.coolConfig.email.port,
      secure: this.coolConfig.email.secure,
      auth: {
        user: this.coolConfig.email.auth.user,
        pass: this.coolConfig.email.auth.pass,
      },
    });

    let subject = '';
    switch(type){
      case 0:
        subject = '注册验证码';
        break;
      case 1:
        subject = '修改密码验证码';
      case 2:
        subject = '绑定验证码';
        break;
    }

    const mailOptions = {
      from: this.coolConfig.email.auth.user,
      to: email,
      subject: subject,
      text: `您的验证码是：${code}，有效期10分钟，请勿泄露给他人。`,
    };

    console.log('this.mailOptions',mailOptions);

    try {
      await transporter.sendMail(mailOptions);
    } catch (error) {
      throw new CoolCommException('邮件发送失败');
    }
  }

  /**
   * 验证验证码
   * @param email 邮箱
   * @param code 验证码
   * @param type 类型 0-注册 1-修改密码 2-绑定邮箱
   */
  async verifyCode(email: string, code: string, type: number) {
    const emailCode = await this.userEmailCodeEntity.findOne({
      where: { email, code, type, status: 0 },
      order: { createTime: 'DESC' },
    });

    if (!emailCode) {
      throw new CoolCommException('验证码错误');
    }

    if (emailCode.expireTime < new Date()) {
      throw new CoolCommException('验证码已过期');
    }

    // 标记验证码已使用
    await this.userEmailCodeEntity.update(emailCode.id, { status: 1 });

    return true;
  }
} 